package com.yalu.util;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import com.yalu.entity.data.Warehousesarea;
import com.yalu.entity.data.WarehousesareaKey;


public class WarehousesareaExcelImportUtil extends BaseExcelImportUtil {
	private List<List<String>> str = null;
	private static final String TITLE = "仓库编码,仓库名称,省,市,区";
	private static int COLUMN_COUNT = 5;

	public WarehousesareaExcelImportUtil() {

	}

	@Override
	public List<String> importExcel(String excelFile) {
		try {
			List<List<String>> array = readExcelReturnArray(excelFile);
			return validate(array);
		} catch (Exception e) {
			e.printStackTrace();
			return errMsg;
		}

	}

	private List<String> validate(List<List<String>> array) {
		for (int rowIndex = 0; rowIndex < array.size(); rowIndex++) {
			List<String> row = array.get(rowIndex);
			if (rowIndex == 0) {
				String msg = validateTitle(row);
				if (StringUtils.isNotBlank(msg)) {
					errMsg.add(msg);
				}
			} else {
				String msg = validateData(rowIndex, row);
				if (StringUtils.isNotBlank(msg)) {
					errMsg.add(msg);
				}
			}
		}
//		
//		Map<String, List<Integer> > map = new HashMap<String, List<Integer>>();
//		Map<String, String> 
//		for (int i = 0; i < dataList.size(); i++) {
//			Warehousesarea entity = (Warehousesarea) dataList.get(i);
//			String code = entity.getWarehousesareaKey().getCode();
//			String name = entity.getWarehousesareaKey().getName();
//			
//			String nameInMap = map.get(code);
//			
//		}
//		
		int size = dataList.size();
		//Set<Integer> checkedNameIndex = new HashSet<Integer>();
		// 从两头轮询开始比较
		for (int i = 0; i < size; i++) {
			Warehousesarea entity = (Warehousesarea) dataList.get(i);
			for (int j = size - 1; j > i; j--) {
				if (i < j) {// 保证不是同一行
					Warehousesarea entityTmp = (Warehousesarea) dataList.get(j);
					
					if (StringUtils.equals(entity.getWarehousesareaKey().getCode(), entityTmp.getWarehousesareaKey().getCode())
							&& !StringUtils.equals(entity.getWarehousesareaKey().getName(), entityTmp.getWarehousesareaKey().getName()))
						{
						String msg = "【仓库名称】栏第【" + (i + 1) + "】笔与第【" + (j + 1)
								+ "】笔，仓库编码相同，仓库名称不同";
						errMsg.add(msg);
						
						//checked
						
					}
				}
			}
		}
		return errMsg;
	}

	/**
	 * @Description: 数据格式校验
	 * @param rowIndex
	 * @param row
	 * @return
	 * @date 2013-10-29 上午12:21:12
	 * @author zch
	 */
	private String validateData(int rowIndex, List<String> row) {
		Warehousesarea entity = new Warehousesarea();
		WarehousesareaKey key = new WarehousesareaKey();
		String msg = "";
		String value = "";
		for (int columnIndex = 0; columnIndex < COLUMN_COUNT; columnIndex++) {
			value = row.get(columnIndex);

			switch (columnIndex) {
			case 0:
				if (StringUtils.isNotBlank(value)) {
					key.setCode(value);
				} else {
					msg = "【仓库编码】栏第【" + rowIndex + "】笔数据不能为空";
					return msg;
				}
				break;
			case 1:
				if (StringUtils.isNotBlank(value)) {
					key.setName(value);
				} else {
					msg = "【仓库名称】栏第【" + rowIndex + "】笔数据不能为空";
					return msg;
				}
				break;
			case 2:
				//if (StringUtils.isNotBlank(value)) {
				key.setArea(value);
//				} else {
//					msg = "【省】栏第【" + rowIndex + "】笔数据不能为空";
//					return msg;
//				}
				break;
			case 3:
				key.setCity(value);
				break;
			case 4:
				key.setDistrict(value);
				break;
			}
			entity.setWarehousesareaKey(key);
		}
		dataList.add(entity);
		return null;
	}

		/**
		 * @Description: 校验标题行
		 * @param row
		 * @return
		 * @date 2013-10-29 上午12:19:39
		 * @author zch
		 */
		private String validateTitle(List<String> row) {
			String msg = "";
			String title = "";
			for (int index = 0; index < COLUMN_COUNT; index++) {
				if (index != COLUMN_COUNT - 1) {
					title = title + row.get(index) + ",";
				} else {
					title = title + row.get(index);
				}

			}
			if (!title.equals(TITLE)) {
				msg = "首行标题依次应为--" + TITLE;
				return msg;
			} else {
				return null;
			}
		}

		public List<List<String>> readExcelReturnArray(String excelFile)
				throws Exception {
			List<List<String>> array = new ArrayList<List<String>>();
			InputStream stream = null;
			try {
				stream = new FileInputStream(excelFile);
				XSSFWorkbook myWorkBook = new XSSFWorkbook(stream);
				XSSFSheet mySheet = myWorkBook.getSheetAt(0);
				Iterator<Row> rowIter = mySheet.rowIterator();
				String cellValue = "";
				int rowIndex = 0;
				while (rowIter.hasNext()) {
					XSSFRow myRow = (XSSFRow) rowIter.next();
					if(myRow==null){
						continue;
					}
					// Iterator<Cell> cellIter = myRow.cellIterator();
					List<String> rowArr = new ArrayList<String>();

					for (int cellnum = 0; cellnum <= COLUMN_COUNT; cellnum++) {
						cellValue = "";
						XSSFCell myCell = myRow.getCell(cellnum);
						if (myCell == null) {
							rowArr.add(cellValue.trim());
							continue;
						}
						// int columnIndex = myCell.getColumnIndex();

						switch (myCell.getCellType()) {
						case XSSFCell.CELL_TYPE_NUMERIC:
							Double numCellValue = myCell.getNumericCellValue();
							boolean isDate = DateUtil.isCellDateFormatted(myCell);
							if (DateUtil.isCellDateFormatted(myCell)) {
								Date t = myCell.getDateCellValue();
								SimpleDateFormat format = new SimpleDateFormat(
										"yyyyMMdd");
								cellValue = format.format(t);
							} else {
								cellValue = numCellValue.intValue() + "";//日期特殊处理
							}
							break;
						case XSSFCell.CELL_TYPE_STRING:
							String strCellString = myCell.getStringCellValue();
							cellValue = strCellString;
							break;
						case XSSFCell.CELL_TYPE_BLANK:
							break;
						}
						rowArr.add(cellValue.trim());
					}
					for (int columnIndex = COLUMN_COUNT; columnIndex > rowArr
							.size();) {
						rowArr.add("");
					}
					//不加入空行数据
					for(String str : rowArr){
						if(!str.equals("")){
							array.add(rowArr);
							break;
						}
					}
					rowIndex++;
				}
			} catch (FileNotFoundException e) {
				e.printStackTrace();
				throw e;
			} catch (IOException e) {
				e.printStackTrace();
				throw e;
			} finally {
				if (stream != null) {
					try {
						stream.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					}
				}
			}

			return array;
		}

		public List<List<String>> getStr() {
			return str;
		}

		public void setStr(List<List<String>> str) {
			this.str = str;
		}

	}
